<template>
  <div>
    <common-head title="用户注册"/>
    <van-form @submit="onSubmit">
      <van-field
        v-model="user.username"
        name="username"
        label="用户名"
        placeholder="用户名/手机/邮箱"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="user.nick"
        name="nick"
        label="昵称"
        placeholder="请输入昵称"
        :rules="[{ required: true, message: '请填入昵称' }]"
      />
      <van-field
        v-model="user.pwd"
        type="password"
        name="pwd"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <!-- 联系人地区 -->
        <van-field
          label="地区"
          name="loacltion"
          :value="areaStr"
          placeholder="请选择省/市/区"
          readonly
          :rules="[{ required: true,}]"
          @click-input="showArea=true"
        />
        <!-- 省市区弹框 -->
        <van-popup v-model="showArea" position="bottom" round>
          <van-area
            :area-list="areaList"
            @confirm="onConfirm"
            @cancel="showArea = false"
          />
        </van-popup>
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { areaList } from '@vant/area-data'
import { doRegister } from '_api'
import CommonHead from '_components/CommonHead.vue'
export default {
  name: 'Register',
  data () {
    return {
      user: {
        username: '',
        pwd: '',
        nick: '',
        province: '',
        city: ''
      },
      areaList,
      showArea: false, // 控制地区弹窗
      areaStr: ''
    }
  },
  methods: {
    onSubmit () {
      doRegister(this.user).then(res => {
        if (res.data.code === 0) {
          this.$toast.success({
            message: '注册成功',
            duration: 1000,
            onClose: () => {
              this.$router.replace('/login')
            }
          })
        }
      })
    },
    // 显示选择的省市区
    onConfirm (data) {
      // 显示用户选择的省市区
      const arr = []
      data.forEach(item => {
        arr.push(item.name)
      })
      this.areaStr = arr.join('/')
      // 将省市区id存入表单字段
      this.user.province = data[0].name
      this.user.city = data[1].name
      this.showArea = false
    },
    onFailed (errorInfo) {
      console.log('failed', errorInfo)
    }
  },
  components: {
    CommonHead
  }
}
</script>

<style scoped>

</style>
